import { defineStore } from "pinia";
import { ref } from "vue";
import http from "../utils/http";
import { ElMessage } from "element-plus";

interface Gateway {
    id: number;
    name: string;
    ip: string;
    isConnected: boolean
}

export const gatewayStore = defineStore('gateway', () => {
    // 网关列表
    const gatewayList = ref<Gateway[]>([]);

    // 当前激活的网关ID
    const activeGatewayId = ref<number>(1);

    // 当前ip地址
    const currentIp = ref<string>('');

    const debug = ref<boolean>(false)

    const fetchDebugMode = async (): Promise<boolean> => {
      let ret = await http.adminInstance.get("/admin/getDebugMode")
      if (ret.data.code === 200) {
          debug.value = ret.data.data.isDebug === "true" ? true : false
          return debug.value
      }
      return false
   }
    // 获取网关列表
    const fetchGatewayList = async () => {
      try {
        const res = await http.instace.get("/socket/getGatewayList");
        const newList = res.data.data;
        gatewayList.value = newList.sort((a: any, b: any) => Number(a.ip.split('.')[3]) - Number(b.ip.split('.')[3]));
        currentIp.value = newList[0].ip;// 初始化时设置为第一个网关
        currentIp.value = newList[0]?.ip || '';
        activeGatewayId.value = newList[0]?.id || 1;
      } catch (error) {
        console.error("获取网关列表失败:", error);
        ElMessage.error("用户网关列表获取失败，注意是不是ip地址配置错误呢")
      }
     
    };
    const refreshGatewayList = async (newList: any) => { 
      try {
        if (gatewayList.value.length === 0 && newList.length !== gatewayList.value.length) {
        // 说明时初始化第一次调用网关列表
        gatewayList.value = newList.sort((a: any, b: any) => Number(a.ip.split('.')[3]) - Number(b.ip.split('.')[3]));
        activeGatewayId.value = gatewayList.value[0].id;
        currentIp.value = gatewayList.value[0].ip;
        return
      }
      const isSame =
        gatewayList.value.length === newList.length &&
        gatewayList.value.every((g, i) => g.id === newList[i].id && g.ip === newList[i].ip && g.isConnected === newList[i].isConnected);
      if (!isSame) {
        const oldGatewayIp = currentIp.value;
        gatewayList.value = newList.sort((a: any, b: any) => Number(a.ip.split('.')[3]) - Number(b.ip.split('.')[3]))
        console.log(newList.sort((a: any, b: any) => Number(a.ip.split('.')[3]) - Number(b.ip.split('.')[3])))
        console.log('网关列表更新', gatewayList.value)

        if (gatewayList.value.length > 0) {
          // 只有当前activeGatewayId不在新列表中时，才切换到第一个
          const exist = gatewayList.value.some(g => g.ip === oldGatewayIp);
        
          if (!exist) {
            activeGatewayId.value = gatewayList.value[0].id;
            currentIp.value = gatewayList.value[0].ip;
          }
        }
      }
      } catch(err) {
         if (gatewayList.value.length === 0 && newList.length !== gatewayList.value.length) {
        // 说明时初始化第一次调用网关列表
        gatewayList.value = newList
        activeGatewayId.value = gatewayList.value[0].id;
        currentIp.value = gatewayList.value[0].ip;
        return
      }
      const isSame =
        gatewayList.value.length === newList.length &&
        gatewayList.value.every((g, i) => g.id === newList[i].id && g.ip === newList[i].ip && g.isConnected === newList[i].isConnected);
      if (!isSame) {
        const oldGatewayIp = currentIp.value;
        gatewayList.value = newList.sort((a: any, b: any) => Number(a.ip.split('.')[3]) - Number(b.ip.split('.')[3]))
        console.log('网关列表更新', gatewayList.value)

        if (gatewayList.value.length > 0) {
          // 只有当前activeGatewayId不在新列表中时，才切换到第一个
          const exist = gatewayList.value.some(g => g.ip === oldGatewayIp);
        
          if (!exist) {
            activeGatewayId.value = gatewayList.value[0].id;
            currentIp.value = gatewayList.value[0].ip;
            
          }
        }
      }
      }

    };
    // 切换网关
    const switchGateway = (id: number) => {
        activeGatewayId.value = id;
        // 更新当前IP地址
        const selectedGateway = gatewayList.value.find(g => g.id === id);
        if (selectedGateway) {
            currentIp.value = selectedGateway.ip;
        }
        // 在这里可以添加切换网关后需要执行的逻辑，
        // 比如通知其他模块清空或重新加载数据
        console.log(`已切换到网关 ${id}, IP: ${currentIp.value}`);

    };

    // 为了向后兼容，添加getGatewayList别名
    const getGatewayList = fetchGatewayList;

    // 通过ip地址映射这个网关名称
    const gatewayNameMap = (ip: string): string => {
        const gateway = gatewayList.value.find(g => g.ip === ip);
        return gateway ? gateway.name : '';
    };

    return {
        gatewayList,
        activeGatewayId,
        debug,
        switchGateway,
        fetchGatewayList,
        getGatewayList,
        currentIp,
        gatewayNameMap,
        fetchDebugMode,
        refreshGatewayList
    }
});